﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Doo.Controls
{
    /// <summary>
    /// 注册要生成的地方，内部的控件直属上级为NamingContainer的ScriptObject。若NamingContainer为PlaceHolder或Page，则为$Page
    /// </summary>
    [ToolboxItem(true)]
    [ToolboxData("<{0}:ControlArea runat=server></{0}:ControlArea>")]
    public class ControlArea : System.Web.UI.HtmlControls.HtmlContainerControl
    {
        public override string TagName
        {
            get
            {
                return "div";
            }
        }

        const string pageitem = "__doo__controlarea";

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            List<string> areaids = Page.Items[pageitem] as List<string>;
            if (areaids == null)
            {
                areaids = new List<string>();
                Page.Items[pageitem] = areaids;
                Page.PreRenderComplete += new EventHandler(Page_PreRenderComplete);
            }
            var parentObj = (NamingContainer as Scripts.IUseScriptObject);
            string objid = (parentObj == null || parentObj.ScriptObject == null) ? "" : parentObj.ScriptObject.ClientID;

            areaids.Add(ClientID);
            areaids.Add(objid);

        }

        void Page_PreRenderComplete(object sender, EventArgs e)
        {
            List<string> areaids = Page.Items[pageitem] as List<string>;
            string output = string.Join("\",\"", areaids.ToArray());

            string script = string.Format("Doo.PageAreas=[\"{0}\"];", output);
            ScriptManager.RegisterStartupScript(this, this.GetType(), this.ClientID, script, true);
        }

    }
}
